package com.hlf.common.utils;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

/**
 * 报文发送类
 * 
 * @author LHL
 * 
 */
public class Sender {

    private final Logger log = LoggerFactory.getLogger(Sender.class);

    private String cookies;//

    public HttpURLConnection createUrl(String url) throws Exception {
        URL httpurl = new URL(url);
        HttpURLConnection http = null;
        try {
            http = (HttpURLConnection) httpurl.openConnection();
        } catch (Exception e) {
            log.error("open connection error!");
        }
        http.setConnectTimeout(20000);
        http.setReadTimeout(20000);
        return http;
    }

    public String sendHttpReq(String url, JSONObject obj, String charset)
            throws Exception {

        StringBuffer buffer = new StringBuffer();
        HttpURLConnection httpurl = null;
        String charEncoding = "UTF-8";
        if (!"".equals(charset)) {
            charEncoding = charset;
        }

        try {
            httpurl = createUrl(url);
            httpurl.setDoOutput(true);
            httpurl.setRequestMethod("POST");
            httpurl.setRequestProperty("Content-Type", "application/json");
            httpurl.setRequestProperty("Accept-Charset", "utf-8");
            DataOutputStream out = new DataOutputStream(
                    httpurl.getOutputStream());
            out.write(obj.toString().getBytes("utf-8"));
            out.flush();
            out.close();

            InputStream in = httpurl.getInputStream();
            int code = httpurl.getResponseCode();
            if (code == 200) {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(in, charEncoding));
                String line;
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }
            } else {
                log.error("no response");
            }
        } catch (Exception e) {
            log.error("operate failed! url is {}", url, e);
            return null;
        } finally {
            closeHttpRequest(httpurl);
        }
        return buffer.toString();
    }

    /**
     *
     * @param url
     *            请求的路径
     * @param content
     *            发送的内容
     * @param isPost
     *            是否为post请求
     * @param saveCookie
     *            是否保存Cookie
     * @param charset
     *            字符集
     * @return
     * @throws Exception
     */
    public String sendHttpReq(String url, String content, boolean isPost,
            boolean saveCookie, String charset) throws Exception {
        StringBuffer buffer = new StringBuffer();
        HttpURLConnection httpurl = null;
        String charEncoding = "utf-8";
        if (!"".equals(charset)) {
            charEncoding = charset;
        }

        try {
            if (isPost) {
                httpurl = createUrl(url);
                httpurl.setDoOutput(true);
                httpurl.setRequestMethod("POST");
                httpurl.setRequestProperty("Content-Type",
                        "application/x-www-form-urlencoded");
                OutputStream os = httpurl.getOutputStream();
                os.write(content.getBytes("utf-8"));
                os.flush();
                os.close();
            } else {
                httpurl = createUrl(url + content);
            }
            InputStream in = httpurl.getInputStream();
            if (saveCookie) {
                List<String> list = ((Map<String, List<String>>) httpurl
                        .getHeaderFields()).get("Set-Cookie");
                for (String temp : list) {
                    cookies += temp + "; ";
                }
            }
            int code = httpurl.getResponseCode();
            if (code == 200) {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(in, charEncoding));
                String line;
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }
            } else {
                log.error("no response");
            }
        } catch (Exception e) {
            log.error("operate failed! url is {}", url, e);
            return null;
        } finally {
            closeHttpRequest(httpurl);
        }
        return buffer.toString();
    }

    public void closeHttpRequest(HttpURLConnection httpReq) {
        if (httpReq != null) {
            httpReq.disconnect();
        }
    }

    public String getCookies() {
        return cookies;
    }

    public void setCookies(String cookies) {
        this.cookies = cookies;
    }

    public static void main(String[] args) throws Exception {

//        JSONObject obj = new JSONObject();
        /*
         * obj.element("account", "15112432052"); obj.element("orderId",
         * "C20160224104252772945");
         */
        String content = "<xml><mch_id>7551000001</mch_id><nonce_str>0.89832560984402090</nonce_str><notify_url>http://120.24.189.198/vvCard/pay/notify</notify_url><body>东莞市坚野网络科技有限公司门店</body><out_trade_no>920160913090058</out_trade_no><total_fee>100</total_fee><service>pay.weixin.native</service><mch_create_ip>113.105.132.50</mch_create_ip><sign>432EF2D54FB55ADBB9FD91C8DC5F362A</sign></xml>";
        Sender send = new Sender();
        String result =send.sendHttpReq("https://pay.swiftpass.cn/pay/gateway", content, true, false, "UTF-8");
        System.out.println(result);

    }

}
